//
//  MessageReceiver.swift
//  ShareUmbrella
//
//  Created by keng fu on 2017/9/20.
//  Copyright © 2017年 尧尚信息科技. All rights reserved.
//

import UIKit
import YSKit
import SwiftyJSON
import SDWebImage

class MessageReceiver: NSObject {
    static let shared = MessageReceiver()
    
    var viewForContainer = UIView()
    var viewForNotify = UIView()
    public var nickNameForNotify = UILabel()
    var imageForNotify = UIImageView()
    
    var btnAcceptForNotify = UIButton()
    var btnRefuseForNotify = UIButton()
    private var timer:Timer?
    private var info: JSON?

    private override init() {
        super.init()
        self.createView()
    }
    
    func listenNotification(){
        NotificationCenter.default.addObserver(self, selector: #selector(showRecipientsDialog(notification:)), name: SOSNotifcation, object: nil)
    }
   private func createView() {
        let window = APP.window
        self.viewForContainer.ys.customize { (view) in
            view.backgroundColor = UIColor(colorLiteralRed: 0, green: 0, blue: 0, alpha: 0.4)
            window?.addSubview(view)
            view.isHidden = true
            view.snp.makeConstraints({ (make) in
                make.edges.equalTo((window)!)
            })
        }
        
        self.viewForNotify.ys.customize { (view) in
            self.viewForContainer.addSubview(view)
            view.backgroundColor = UIColor.white
            view.layer.cornerRadius = 10
            view.layer.masksToBounds = true
            view.snp.makeConstraints({ (make) in
                make.center.equalTo((self.viewForContainer.snp.center))
                make.leading.equalTo((self.viewForContainer.snp.leading)).offset(30)
                make.trailing.equalTo((self.viewForContainer.snp.trailing)).offset(-30)
                make.height.equalTo(170)
            })
        }
        
        self.imageForNotify.ys.customize({ (view) in
            self.viewForNotify.addSubview(view)
            view.image = UIImage(named: "头像7")
            view.layer.masksToBounds = true
            view.layer.cornerRadius = 60/2
            view.snp.makeConstraints({ (make) in
                make.top.equalTo(self.viewForNotify.snp.top).offset(20)
                make.leading.equalTo(self.viewForNotify.snp.leading).offset(20)
                make.height.width.equalTo(60)
            })
        })
        
        self.nickNameForNotify.ys.customize({ (view) in
            self.viewForNotify.addSubview(view)
            view.numberOfLines = 3
            view.textColor = UIColor.lightGray
            view.text = "求助者_在向你求助"
            view.snp.makeConstraints({ (make) in
                make.trailing.equalTo(self.viewForNotify.snp.trailing).offset(-20)
                make.leading.equalTo(self.imageForNotify.snp.trailing).offset(20)
                make.centerY.equalTo(self.imageForNotify)
            })
            
        })
        
        btnRefuseForNotify.ys.customize({ (view) in
            view.setTitle("残忍拒绝", for: .normal)
            view.layer.cornerRadius = 20
            view.layer.masksToBounds = true
            self.viewForNotify.addSubview(view)
            view.backgroundColor = UIColor.lightGray
            
            view.snp.makeConstraints({ (make) in
                make.trailing.equalTo(self.nickNameForNotify.snp.trailing)
                make.bottom.equalTo(self.viewForNotify.snp.bottom).offset(-20)
                make.width.equalTo(self.viewForNotify.snp.width).dividedBy(3)
                make.height.equalTo(40)
            })
            
        })
        
        
        _ = btnRefuseForNotify.rx.tap
            .takeUntil(self.rx.deallocated)
            .subscribe(onNext: { [weak self](RxGestureTypeOptions) in
                
                guard let `self` = self else {
                    return
                }
                HUD.show()
                
                _ = YSNetWorkManager.provider.requestJSON(YSStructTarget(ProvideAPI.refuseHelpAction(token: Auth.token, helpid: User.statusInfo.value?.info["info"]["helpid"].stringValue ?? ""))).subscribe(onNext: {(data) in
                    
                    User.getStatus {
                        HUD.hide()
                        self.hide()
                    }
                }, onError: {[weak self](ErrorType) in
                    
                    guard let  `self` = self else {
                        return
                    }
                    HUD.hide()
                    self.hide()
                    self.handle(withError: ErrorType)
                })
                
            })
        
        btnAcceptForNotify.ys.customize({ (view) in
            view.setTitle("欣然接受", for: .normal)
            view.layer.cornerRadius = 20
            view.layer.masksToBounds = true
            self.viewForNotify.addSubview(view)
            view.backgroundColor = UIColor(colorLiteralRed: 61/255.0, green: 170/255.0, blue: 109/255.0, alpha: 1)
            
            view.snp.makeConstraints({ (make) in
                make.leading.equalTo(self.imageForNotify.snp.leading)
                make.bottom.equalTo(self.viewForNotify.snp.bottom).offset(-20)
                make.width.equalTo(self.viewForNotify.snp.width).dividedBy(3)
                make.height.equalTo(40)
            })
            
        })
        
        _ = btnAcceptForNotify.rx.tap
            .takeUntil(self.rx.deallocated)
            .subscribe(onNext: { [weak self](RxGestureTypeOptions) in
                
                guard let `self` = self else {
                    return
                }
                HUD.show()
                _ = YSNetWorkManager.provider.requestJSON(YSStructTarget(ProvideAPI.acceptHelpAction(token: Auth.token, helpid: self.info?["info"]["helpid"].stringValue ?? ""))).subscribe(onNext: {(data) in
                    
                    User.getStatus {
                        HUD.hide()
                        //调到帮助页面
                        self.hide()
                        guard let _ = APP.currentVC as? RecipientsVC else {
                            APP.currentVC?.ys.push(RecipientsVC())
                            return
                        }
                    }
                    
                }, onError: {[weak self](ErrorType) in
                    HUD.hide()
                    guard let  `self` = self else {
                        return
                    }
                    self.hide()
                    self.handle(withError: ErrorType)
                })
                
            })
        

    }
    func hide(){
        self.viewForContainer.isHidden = true
        
        self.timer?.invalidate()
        self.timer = nil
    }
    func showRecipientsDialog(notification: Notification){
        
        if self.timer == nil {
            //启动定时器，如果60秒只能用户还么操作，则相当于自动拒绝了
            self.timer = Timer.scheduledTimer(withTimeInterval: 60, repeats: false, block: { [weak self] (timer) in
                guard let  `self` = self else {
                    return
                }
                self.hide()
                self.timer = nil
            })
        }
        print("收到帮助请求。。。。。。。")
        self.info = User.statusInfo.value?.info
        let name = self.info?["info"]["name"].string ?? self.info?["info"]["phone"].string
        if  let n = name {
            self.nickNameForNotify.text = "求助者\(n)正在向您求助"
        }
        if let avator = self.info?["info"]["avator"].string {
            self.imageForNotify.sd_setImage(with: URL(string: avator), placeholderImage: UIImage(named: "头像7"))
        }

        
        if self.viewForContainer.isHidden,  let window = APP.window {
            window.bringSubview(toFront: self.viewForContainer)
            self.viewForContainer.isHidden = false

        }

        
    }
}
